package com.itzdm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzdm.reggie.common.basecontext.BaseContext;
import com.itzdm.reggie.entity.ShoppingCart;
import com.itzdm.reggie.mapper.ShoppingCartMapper;
import com.itzdm.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Override
    public void saveShoppingCart(ShoppingCart shoppingCart) {
        //设置用户ID
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //查询是否存在该菜品
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        if (dishId == null) {
            //菜品ID为空时，添加的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }else {
            //不为空时，添加菜品
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        }
        ShoppingCart cart = getOne(queryWrapper);

        if (cart != null){
            //如果存在，数量加1
            Integer number = cart.getNumber();
            cart.setNumber(number + 1);
            updateById(cart);
        }else {
            //不存在，数量默认为1
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            save(shoppingCart);
        }
    }

    @Override
    public void sub(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        if (dishId != null){
            //删除的是菜品
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
            ShoppingCart cart = getOne(queryWrapper);
            if (cart.getNumber() == 1){
                removeById(cart.getId());
            }else {
                cart.setNumber(cart.getNumber() - 1);
                updateById(cart);
            }
        }else {
            //删除的套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
            ShoppingCart cart = getOne(queryWrapper);
            if (cart.getNumber() == 1){
                removeById(cart.getId());
            }else {
                cart.setNumber(cart.getNumber() - 1);
                updateById(cart);
            }
        }
    }
}
